<?php

class RecyclesController extends AppController {

	var $name = 'Recycles';

	private function _list($modelClass) {
    	$this->loadModel($modelClass);
    	$this->name = Inflector::pluralize($this->modelClass);
    
    	list($plugin, $modelClass) = pluginSplit($modelClass, false);
    	$options = $this->request->data;
    	$_options = array(
    			'rows' => 30,
    			'page' => 1,
    			'sidx' => 'id',
    			'sord' => 'desc',
    	);
    
    	if (empty($options))
    		$options = array();
    	foreach ($options as $key => $val) {
    		if (empty($val)) {
    			unset($options[$key]); // 传入空的值注销，用默认的$_options中的值
    		}
    	}
    	$_schema_keys = array_keys($this->Recycle->schema());
    	if (in_array('sort', $_schema_keys)) {
    		$_options['sidx'] = 'sort';
    	}
    	if(is_array($options)) {
            $options = array_merge($_options, $options);
        }
        else{
            $options = $_options;
        }

    	$search_groupby = array();
    	$conditions = array('model'=>$modelClass);
    	
    	if (is_array($this->params['named']) && !empty($this->params['named'])) {
    		foreach ($this->params['named'] as $k => $v) {
    			if(strrpos('.',$k)!==false){
    				$conditions[$k] = $v;
    			}
    			else{
    				$conditions[$modelClass . '.'.$k] = $v;
    			}
    		}
    	}
    
    	$has_step_conditions = false;
    
    	$fields = $_schema_keys;
    
    	if (isset($_POST['_search']) && $_POST['_search'] == 'true' && $_POST['filters']) {
    		$filters = json_decode($_POST['filters'], true);
    		foreach ($filters['rules'] as $v) {
    			$f_k = $v['field'];
    			if($f_k!='name') continue; //回收站的数据仅支持按name搜索（在recycle表中）
    			$f_v = $v['data'];
    			switch ($v['op']) {
    				case 'eq': //等于
    					$f_k = $v['field'];
    					break;
    				case 'ne': //不等于
    					$f_k = $v['field'] . ' <>';
    					break;
    				case 'le':  // 小于等于
    					$f_k = $v['field'] . ' <=';
    					break;
    				case 'lt':  // 小于
    					$f_k = $v['field'] . ' <';
    					break;
    				case 'ge':  // 大于等于
    					$f_k = $v['field'] . ' >=';
    					break;
    				case 'gt':  // 大于
    					$f_k = $v['field'] . ' >';
    					break;
    				case 'bw':  // 开始于
    					$f_k = $v['field'] . ' like';
    					$f_v = $v['data'] . '%';
    					break;
    				case 'bn':  // 不开始于
    					$f_k = $v['field'] . ' not like';
    					$f_v = $v['data'] . '%';
    					break;
    				case 'ew':  // 结束于
    					$f_k = $v['field'] . ' like';
    					$f_v = '%' . $v['data'];
    					break;
    				case 'en':  // 不结束于
    					$f_k = $v['field'] . ' not like';
    					$f_v = '%' . $v['data'];
    					break;
    				case 'cn':  // 包含
    					$f_k = $v['field'] . ' like';
    					$f_v = '%' . $v['data'] . '%';
    					break;
    				case 'nc':  // 不包含
    					$f_k = $v['field'] . ' not like';
    					$f_v = '%' . $v['data'] . '%';
    					break;
    				case 'in':  // 属于
    					$f_k = $v['field'];
    					$in_values = explode(',', $v['data']);
    					$f_v = $in_values;
    					break;
    				case 'ni':  // 不属于
    					$f_k = $v['field'] . ' NOT';
    					$in_values = explode(',', $v['data']);
    					$f_v = $in_values;
    					break;
    			}
    			$f_k = $modelClass . '.' . $f_k;
    			if ($filters['groupOp'] == 'AND') {
    				$conditions[$f_k] = $f_v;
    			} elseif ($filters['groupOp'] == 'OR') {
    				$conditions['OR'][$f_k] = $f_v;
    			}
    		}
    	}
    	$sort_order = '';
    	//		if(in_array('sort',$_schema_keys))
    		//		{
    		//			$sort_order = $modelClass.'.sort desc,';
    		//		}
    	if (in_array($options['sidx'], $_schema_keys)) {
    		$sort_order .=  'Recycle.' . $options['sidx'] . ' ' . $options['sord'];
    	} else {
    		$sort_order .= $options['sidx'] . ' ' . $options['sord'];
    	}

    	$searchoptions = array(
    			'conditions' => $conditions,
    			'order' => $sort_order,
    			'limit' => $options['rows'],
    			'page' => $options['page'],
    			'group' => $search_groupby,
    	);
    	$joinmodel_fields = array();
    	$alias = 0;
    	$extSchema = $this->{$modelClass}->getExtSchema();
    	$ext_options = array();
    
        $this->Recycle->recursive = -1;
    	$datas = $this->Recycle->find('all', $searchoptions);
    	$count = $this->Recycle->find('count', array(
    			'conditions' => $conditions,
                'recursive' => -1,
    			// 'group' => $search_groupby , 含有group的查询，计算总数时，要用嵌套查询 select count(*) from (select ***) tabl
    	));
    	//        print_r($count);
    	if ($count > 0) {
    		$total_pages = ceil($count / $options['rows']);
    	} else {
    		$total_pages = 0;
    	}
    	$rows = array();
    	$control_name = Inflector::tableize($modelClass);
    	
    	foreach ($datas as $item) {
    		// 还原回收站序列号的数据内容
    		$item = array_merge($item,unserialize($item['Recycle']['content']));
    		foreach ($fields as $field_name) {
    			if (!empty($extSchema[$field_name]['formtype']) && $extSchema[$field_name]['formtype'] == 'file') {
                    if(is_array($item['Uploadfile'])){
                        $upload_files = array();
                        foreach ($item['Uploadfile'] as $singlefile) {
                            $upload_files[] = '<a href="' . Router::url('/' . $singlefile['fspath']) . '" target="_blank">' . $singlefile['name'] . '</a>';
                        }
                        $item[$modelClass][$field_name] = implode('<br/>', $upload_files);
                    }
    			} elseif ($extSchema[$field_name]['formtype'] == 'ckeditor' || $extSchema[$field_name]['formtype'] == 'textarea') {
    				$item[$modelClass][$field_name] = usubstr($item[$modelClass][$field_name],0,300);
    			}
    			elseif($field_name!='parent_id' && $extSchema[$field_name]['selectvalues'] && in_array($extSchema[$field_name]['formtype'], array('select', 'checkbox', 'radio'))){
    				$tmpval = $item[$modelClass][$field_name];
    				$item[$modelClass][$field_name] = $ext_options[$field_name][$tmpval];
    			}
    			$item[$modelClass][$field_name] = htmlspecialchars($item[$modelClass][$field_name]);
    		}
    		if (in_array('coverimg', $fields) && $item[$modelClass]['coverimg']) {
    			$img_url = Router::url($item[$modelClass]['coverimg']);
    			$sitepaths = Router::getPaths();
    			$img_url = str_replace($sitepaths['base'], '', $img_url);
    			//echo "$img_url<br/>";
    			$item[$modelClass]['coverimg'] = '<img src="' . $img_url . '" width="100"/>';
    		}
    		/*******重要： action的li之间要一个紧连着一个 ，不要有换行或空格，否则会引起格式错乱。****** */
    		$actions = '';
			if($this->AclFilter->check($this->name,'admin_restore')){
				$actions .= '<li class="ui-state-default grid-row-restore"><a class="btn btn-small" href="#" data-confirm="'.__('Are you sure to restore').'" onclick="ajaxAction(\'' . Router::url(array('controller' => 'Recycles', 'action' => 'restore_recycle', 'plugin' => strtolower($plugin), 'admin' => true,$modelClass, $item['Recycle']['data_id'],'ext'=>'json')) . '\',null,null,\'deleteGridRow\',this)" title="' . __('Restore') . '"><i class="glyphicon glyphicon-retweet"></i></a></li>';
			}
			if($this->AclFilter->check($this->name,'admin_delete')){
				$actions .= '<li class="ui-state-default grid-row-delete"><a class="btn btn-small" href="#" data-confirm="'.__('Are you sure to delete').'" onclick="ajaxAction(\'' . Router::url(array('controller' => 'Recycles', 'action' => 'delete', 'plugin' => strtolower($plugin), 'admin' => true, $item['Recycle']['id'],'ext'=>'json')) . '\',null,null,\'deleteGridRow\',this)" title="' . __('Delete') . '"><i class="glyphicon glyphicon-remove"></i></a></li>';
			}
    		$actions .= '<li class="ui-state-default grid-row-view"><a class="btn btn-small" href="' . Router::url(array('controller' => 'Recycles', 'action' => 'view', 'plugin' => strtolower($plugin), 'admin' => true, $item['Recycle']['id'])) . '" title="' . __('View') . '"><i class="glyphicon glyphicon-info-sign"></i></a></li>';
    		
    		$actions .= $this->Hook->call('gridDataAction', array($modelClass, $item[$modelClass]));
    		
    		$item[$modelClass]['actions'] = $actions;
    
    		$params = array($modelClass, &$item[$modelClass]);
    		$this->Hook->call('gridList', $params);
    		$item[$modelClass]['actions'] = '<ul class="ui-grid-actions">' . $item[$modelClass]['actions'] . '</ul>';
    		$rows[] = $item[$modelClass];
    	}
    
    	$datalist = array(
    			'records' => $count,
    			'page' => $options['page'],
    			'limit' => $options['rows'],
    			'total' => $total_pages,
    			'rows' => $rows,
    	);
    
    	$this->set('datalist', $datalist);
    	$this->set('_serialize', 'datalist');
    }


	/**
     * 列表页
     */
    function admin_list($model='') {
    	if($this->request->params['ext']=='json'){
    		$modelClass = $_GET['model']?$_GET['model']:($model?$model:$this->modelClass);
    		$this->_list($modelClass);
    		return;
    	}
    	elseif($_GET['type']=='select'){
    		$this->_select(); // dialog显示本模块列表数据共选择，用于与其他模块建立关联。如添加新闻产品等的选择标签。
    		return;
    	}
    	$requeststr = 'model=' . urlencode($model);
        $model_setting = Configure::read($model);   

        // 加载表单默认值。用于搜索表单、行内编辑
        $this->__loadFormValues($model);

        $this->loadModel($model);
        $ext_schema = $this->{$model}->getExtSchema();
        $fileds = array_keys($ext_schema);
        
        if (isset($model_setting['list_fields'])) {
            $listfields = explode(',', $model_setting['list_fields']);
        } else {
            $listfields = $fileds;
        }
        $col_names = $fieldlist = '';

        foreach ($fileds as $field) {
        	if ($field !='parent_id' && !in_array($field, $listfields)) {
        		continue;
        	}
        	
            $col_width = '';            
            $col_names .="'" . __d('i18nfield',$model.'_'.$field) . "',";

            $editoptions = '';
            $view_values_name = Inflector::variable(
            	Inflector::pluralize(preg_replace('/_id$/', '', $field))
            );
            if (!empty($this->viewVars[$view_values_name]) && is_array($this->viewVars[$view_values_name])) {
                foreach ($this->viewVars[$view_values_name] as $key => $value) {
                    $editoptions .= "$key:$value;";
                }               
                $editoptions = 'editable: true,edittype:"select",editoptions:{value:"' . substr(preg_replace("/\s/",'',$editoptions), 0, -1) . '"},';
            } elseif (in_array($field, array('password', 'id'))) {
                $editoptions = 'editable: false,';
            } else {
                $editoptions = 'editable: true,';
            }
            
            if ($field == 'id' || 'id' == substr($field, -2)) {
                $col_width = 'width:"30px",';
            } elseif ($field == 'name' || $field == 'title') {
                $col_width = '';
            }//width:"150px",
            elseif (!empty($ext_schema[$field]['type']) && $ext_schema[$field]['type'] == 'datetime') {
                $col_width = 'width:"100px",';
            } elseif (!empty($ext_schema[$field]['type']) && $ext_schema[$field]['type'] == 'integer') {
                $col_width = 'width:"30px",';
            } else {
                $col_width = 'width:"80px",';
            }
       		if (!in_array($field, $listfields)) {
                $fieldlist .="{name:'$field'," . $col_width . $editoptions . "index:'$field',hidden:true,searchoptions:{searchhidden:false},search:true}\r\n,";
            }
            else{
            	$fieldlist .="{name:'$field'," . $col_width . $editoptions . "index:'$field',search:true}\r\n,";
            }
        }
//		$col_names=substr($col_names,0,-1);
//		$fieldlist=substr($fieldlist,0,-1);
        $col_names.="'" . __('Actions') . "'";
        $fieldlist.="{name:'actions',index:'actions',width:120,sortable:false,hidedlg:true,search:false}";
		
        $named_str = '';
        foreach($this->request->params['named'] as $key => $val){
        	$named_str .= htmlspecialchars($key) . ':' . urlencode($val) . '/';
        }
        
        $is_tree_model = false;
        $grid_action ='jqgrid';
    	
    	if(!empty($named_str)){
    		$grid_action .= '/'.$named_str;
    	}
    	
    	if($this->AclFilter->check($this->name,'admin_delete')){
    		$this->set('allow_delete', true);
    	}
    	if($this->AclFilter->check($this->name,'admin_restore')){
    		$this->set('allow_restore', true);
    	}
    	
    	$this->set('grid_action', $grid_action);
        $this->set('table_fields', $fileds);
        $this->set('fieldlist', $fieldlist);
        $this->set('col_names', $col_names);
        $this->set('checked_fields', $listfields); // list_fields选中字段
        $this->set('requeststr', $requeststr);
        
        $this->set('modelinfo', $this->{$this->modelClass}->getModelInfo());
        $this->set('schema', $this->{$this->modelClass}->schema());
    }
    
    public function admin_delete($ids= NULL){
    	if( !in_array(1,$this->currentUser['role_id']) ) {
    		$this->__message('仅超级管理员能删除回收站的数据。');
    	}
    	parent::admin_delete($ids);
    }


	/**
     * 恢复删除标记
     * @param $id
     */
    function admin_restore_recycle($model, $ids = null) {
    	if(is_array($_POST['ids'])&& !empty($_POST['ids'])){
    		$ids = $_POST['ids'];
    	}
    	else{
	        if (!$ids) {
	            $result_info = array('error' => __('Restore error'));
	            $this->set('result_info', $result_info);
        		$this->set('_serialize', 'result_info');
        		return;
	        }
	        $ids = explode(',', $ids);
    	}

    	$model_obj = loadModelObject($model);

        foreach ($ids as $id) {
            if (!intval($id))
                continue;
            $item = $this->Recycle->find('first',array('conditions'=>array('model'=>$model,'data_id'=>$id)));
            $data = unserialize($item['Recycle']['content']);
            
            if(isset($data[$model]['updated'])) {
                $data[$model]['updated'] = date('Y-m-d H:i:s'); // 回收站恢复数据时，设置更新时间为恢复数据的时间
            }

            if ($model_obj->saveAll($data)) {
            	// 恢复完成后，删除回收站中的数据
            	$this->Recycle->deleteAll(array('model' => $model,'data_id'=>$id), true, true);
//	            $this->Session->setFlash(__('The Data is restore success.', true));
                $result_info = array('success' => __('Restore success'));
            } else {
                $result_info = array('error' => __('Restore error'));
            }
        }
        $this->set('result_info', $result_info);
        $this->set('_serialize', 'result_info');
    }


}
?>